package kassiopeia.agent.peripherals;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import kassiopeia.commons.exception.KassiopeiaException;
import com.google.common.base.Preconditions;
import com.google.common.io.Files;

@Component
public class TemporaryDirectoryStore {

    private static final Logger logger = Logger.getLogger(TemporaryDirectoryStore.class);

    public static final String PREFIX = "tmp";
    public static final String SUFFIX = "store";
    public static final String AGENT_DATA_KEY = "agent.data";

    private String storePath;
    private List<File> items;

    public TemporaryDirectoryStore(String storePath) {
        Preconditions.checkNotNull(storePath);

        try {
            this.storePath = storePath;
            items = new ArrayList<File>();
            Files.createParentDirs(new File(storePath));

            logger.info("Temporary Directory Store created in " + getStorePath());
        } catch(IOException exception) {
            throw new KassiopeiaException("Can't create root directory", exception);
        }
    }

    public TemporaryDirectoryStore() {
        this(System.getProperty(AGENT_DATA_KEY));
    }

    public File createFile() throws IOException {
        File item = File.createTempFile(PREFIX, SUFFIX, new File(getStorePath()));
        items.add(item);
        logger.info("New item created: " + item.getName());
        return item;
    }

    public String getStorePath() {
        return storePath;
    }

    public int getItemsInStoreCount() {
        return items.size();
    }

    public void wipeOut() {
        for(File item : items) {
            deleteQuietly(item);
        }
        items.clear();
        logger.info("wiped out");
    }

    private void deleteQuietly(File item) {
       try {
           Files.deleteRecursively(item);
           logger.info("Item deleted: " + item.getName());
       } catch(IOException exception) {
           logger.error("Error while deleting item: " + item.getName(), exception);
       }
    }
}
